% Test_Segmentation

labels = ['A' 'B' 'C' 'D' 'F' 'G' 'H' 'K' 'M' 'O' 'P' 'S' 'Z']';


for i=6:numel(labels)
    
    class = labels(i);
    path = ['./images/training/' class '/'];
    filenames = dir([path '*.jpg']); filenames = {filenames(:).name};
    
    s = 1;
    for j=1:numel(filenames);
        if s == 1
            figure
        end
        
        filename = filenames{j};
        I = imread([path filename]);
        %G = fspecial('disk',10);
        %Ifilt = imfilter(I,G,'replicate');
        subplot(2,3,s)
        imshow(I)
        
%         mask = GetTrainingMask(I);
%         subplot(2,3,s+3)
%         imshow(mask,[])
        
        labeled = kmeansColor(I,6,'rgb');
        subplot(2,3,s+3)
        %imshow(clear,[])
        segmented_images = cell(1,6);
        
        for k = 1:6
            color = labeled;
            color(labeled ~= k) = 0;
            segmented_images{k} = color;
            segmented_images{k} = imclearborder(segmented_images{k});
        end
        
        mask = segmented_images{1}|segmented_images{2}|segmented_images{3}|segmented_images{4}|segmented_images{5}|segmented_images{6};
        mask = medfilt2(mask,[6 6]);
        se = strel('disk',4);
        mask = imfill(mask,'holes');
        mask = imdilate(mask, se);
        mask = imfill(mask,'holes');
        mask = imerode(mask, se);
        imshow(mask);
        
        cc = bwconncomp(mask);
        
        if cc.NumObjects > 1
            for i = 1:cc.NumObjects
                label = mask;
                label(~cc.PixelIdxList{i}) = 1;
                % call function
            end
        end
        % call function
        
        s = s+1;
        if s == 4
            s = 1;
        end
    end
    close all
end